<script setup lang="ts">
import { message } from '@/utils/message'
import { type PaginationProps } from '@pureadmin/table'
import { FormInstance } from 'element-plus'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
// import { addConfig, updateConfig } from "@/api/system/config";
// import { useDicts } from "@/utils/dict";
import { authUserSelectAll, unallocatedUserList } from '@/api/system/role'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'

import { formatDate } from '@/utils/common'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
// import { DictTag } from "@/components/DictTag";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
  },
  roleId: {
    type: [Number, String, Array],
  },
  data: {
    type: Object,
    default: () => {
      return {}
    },
  },
})

const query = reactive({
  queryParams: {
    userName: undefined,
    phonenumber: undefined,
    roleId: undefined,
  },
})

const { queryParams } = toRefs(query)
const formRef = ref()

const userIds = ref([])
const single = ref(true)
const multiple = ref(true)
const showSelection = true

const dataList = ref([])
const loading = ref(true)
const title = ref(props.title)
const roleId = ref(props.roleId)
const ruleFormRef = ref<FormInstance>()
const formVisible = ref(false)
// const formData = ref(props.data);
// const { sys_normal_disable } = useDicts("sys_normal_disable");

const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true,
})

const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
    hide: ({ checkList }) => !checkList.includes('勾选列'),
  },
  {
    label: '序号',
    type: 'index',
    width: 70,
    hide: ({ checkList }) => !checkList.includes('序号列'),
  },
  {
    label: '用户名称',
    prop: 'userName',
    minWidth: 100,
  },
  {
    label: '邮箱',
    prop: 'email',
    minWidth: 100,
  },
  {
    label: '手机号码',
    prop: 'phonenumber',
    minWidth: 140,
  },
  {
    label: '状态',
    prop: 'status',
    minWidth: 120,
    // cellRenderer: scope => {
    //   return <DictTag options={sys_normal_disable} value={scope.row.status} />;
    // }
  },
  {
    label: '创建时间',
    minWidth: 180,
    prop: 'createTime',
    formatter: ({ createTime }) => formatDate(createTime),
  },
]

/** 查询列表 */
async function onSearch() {
  loading.value = true
  const params = {
    ...queryParams.value,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
  }
  const { rows, total } = await unallocatedUserList(params)
  dataList.value = rows
  pagination.total = total
  loading.value = false
}

/** 改变多选项 */
function handleSelectionChange(selection) {
  userIds.value = selection.map((item) => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 改变分页大小 */
function handleSizeChange(val: number) {
  pagination.pageSize = val
  onSearch()
}

/** 改变当前分页 */
function handleCurrentChange(val: number) {
  pagination.currentPage = val
  onSearch()
}

/** 选择授权用户操作 */
function handleSelectUser() {
  // const roleId = queryParams.value.roleId;
  const uIds = userIds.value.join(',')
  if (uIds == '') {
    message('请选择要分配的用户', { type: 'error' })
    return
  }
  authUserSelectAll({ roleId: roleId.value, userIds: uIds }).then((res) => {
    message(res.msg, { type: 'success' })
    if (res.code === 200) {
      formVisible.value = false
      emit('refresh')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const closeDialog = () => {
  formVisible.value = false
  resetForm(ruleFormRef.value)
}

onMounted(() => {
  onSearch()
})

const emit = defineEmits(['update:visible', 'refresh'])
watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val)
  }
)

watch(
  () => props.visible,
  (val) => {
    formVisible.value = val
  }
)

watch(
  () => props.title,
  (val) => {
    title.value = val
  }
)

// watch(
//   () => props.data,
//   val => {
//     formData.value = val;
//   }
// );
</script>

<template>
  <el-dialog
    v-model="formVisible"
    :title="title"
    :width="800"
    draggable
    :before-close="closeDialog"
  >
    <el-form
      ref="formRef"
      :inline="true"
      :model="queryParams"
      class="bg-el-bg w-[99/100] pl-8 pt-4"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <PureTableBar title="用户列表">
      <template #buttons />
      <template #table>
        <pure-table
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :checkList="showSelection ? ['勾选列'] : []"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        />
      </template>
    </PureTableBar>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSelectUser"> 确定 </el-button>
    </template>
  </el-dialog>
</template>
